package cn.hl.hm.controller;

import cn.hl.hm.constants.DriverStatus;
import cn.hl.hm.constants.DriverVehicleStatus;
import cn.hl.hm.constants.ModelConfig;
import cn.hl.hm.constants.OrderStatus;
import cn.hl.hm.dao.ChannelDiscountMapper;
import cn.hl.hm.dao.DriverMapper;
import cn.hl.hm.dao.OrderMapper;
import cn.hl.hm.dao.RemainCashDescMapper;
import cn.hl.hm.dao.VehicleMapper;
import cn.hl.hm.dao.VtVlMapper;
import cn.hl.hm.entity.*;
import cn.hl.hm.logic.manage.DriverManageLogic;
import cn.hl.hm.service.*;
import cn.hl.hm.util.AppPager;
import cn.hl.hm.util.BeanPicUtil;
import cn.hl.hm.util.FileUtil;
import cn.hl.hm.util.InfoCode;
import cn.hl.hm.util.LoginkUtil;
import cn.hl.hm.util.OSSUtil;
import cn.hl.hm.util.QRCodeUtil;
import cn.hl.hm.util.Result;
import cn.hl.hm.util.TokenProcessor;
import com.vizhuo.logink.LoginkConfig;
import com.vizhuo.smscode.model.SMSCode;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/driverController")
public class DriverController {
	private static final Logger logger = LoggerFactory.getLogger(DriverController.class);
	private final static SimpleDateFormat hhmmSdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	@Autowired
	SMSCodeIService sMSCodeIService;
	@Autowired
	DriverService driverService;
	@Autowired
	VtVlMapper vtVlMapper;
	@Autowired
	OrderService orderService;
	@Autowired
	OrderMapper orderMapper;
	@Autowired
	private BeanPicUtil beanPicUtil;
	@Autowired
	DriverLatitudeLongitudeService dllService;
	@Autowired
	RouteService routeService;
	@Autowired
	UserService userService;
	@Autowired
	@Qualifier("pushToAppServiceImpl")
	private PushToAppIService pushToAppIService;

	@Autowired
	RouteVehiclePriceService rvpService;

	@Autowired
	@Qualifier("loginkConfig")
	private LoginkConfig loginkConfig;

	@Autowired
	LoginkUtil loginkUtil;

	@Autowired
	ChannelDiscountMapper channelDiscountMapper;

	@Autowired
	RemainCashDescMapper rdm;
	
    @Autowired
	private OSSUtil ossutil;
	

	@Autowired
	DriverMapper driverMapper;
	@Autowired
	StsPriceService stsPriceService;
	@Autowired
	DriverVehicleService driverVehicleService;
	@Autowired
	private DriverManageLogic driverManageLogic;
	@Autowired
	private VehicleLengthService vehicleLengthService;
	@Autowired
	private VehicleTypeService vehicleTypeService;
	@Autowired
	private SecurityFeeTypeHistoryService securityFeeTypeHistoryService;
	@Autowired
	private DriverStatusHistoryService driverStatusHistoryService;

	/**
	 * @Title: login @4Description:司机登录 @date: 2017年1月4日 @author: 星矢 @param
	 *         DriverAccount @param pass @param platformId @param request @param
	 *         response @throws IOException void @throws
	 */
	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public String login(@RequestParam String driverAccount, @RequestParam String password, @RequestParam String appId,
			String deviceToken, HttpServletRequest request, HttpServletResponse response) throws IOException {
		logger.info("用户---登录---driverController/login");
		request.setCharacterEncoding("UTF-8");
		Driver record = new Driver();
		record.setDriverAccount(driverAccount);
		record.setPassword(password);
		// if(StringUtils.isNotBlank(appId)){
		// record.setPlatformId(appId);
		// }
		try {
			List<Driver> selectDriver = driverService.selectDriver(record);
			if (null != selectDriver && selectDriver.size() > 0) {// 登录
				Driver result = selectDriver.get(0);
				// 登录
				request.getSession().setAttribute("LOGIN_Driver_ACCOUNT", result.getDriverAccount());
				request.getSession(false).setAttribute("Driver_SECURITY_TOKEN", result.getDeviceToken());
				// 司机登录活跃统计
				driverService.addHotRecord(result.getId(), "2", "1");
				// 更改操作时间
				Driver u = new Driver();
				u.setUpdateTime(new Date());
				u.setId(result.getId());
				if (StringUtils.isNoneBlank(deviceToken)) {
					u.setDeviceToken(deviceToken);
				}
				driverService.updateDriver(u);
				Result.ok(result, InfoCode.SUCCESS, response);
				return null;
			} else {
				Result.ok(null, InfoCode.AUTH_ERROR, response);
				return null;

			}
		} catch (Exception e) {
			Result.ok(null, InfoCode.FAILURE, response);
			return null;
		}

	}

	/**
	 * @Title: checkMsg @Description: 忘记密码验证 验证码 @date: 2017年1月4日 @author:
	 *         星矢 @param DriverAccount @param verifyCode @param
	 *         platformId @param request @param response @return @throws
	 *         IOException String @throws
	 */
	@RequestMapping(value = "/checktMsgCode", method = RequestMethod.POST)
	public String checkMsg(@RequestParam String driverAccount, @RequestParam String verifyCode,
			@RequestParam String appId, @RequestParam String type, // 1 找回密码
			HttpServletRequest request, HttpServletResponse response) throws IOException {
		logger.info("用户---忘记密码验证---driverController/checktMsgCode");
		request.setCharacterEncoding("UTF-8");
		Driver record = new Driver();
		record.setDriverAccount(driverAccount);
		try {
			if (type.equals("3")) {
				List<Driver> selectDriver = driverService.selectDriver(record);
				if (null != selectDriver && selectDriver.size() > 0) {
					SMSCode sMSCode = new SMSCode();
					sMSCode.setMobile(driverAccount);
					sMSCode.setCode(verifyCode);
					SMSCode smsCode = sMSCodeIService.findCode(sMSCode);
					if (smsCode == null) {
						Result.ok(null, InfoCode.MESSAGE_ERROR, response);
						return null;
					}
					// 司机存在且验证码正确
					Result.ok(null, InfoCode.SUCCESS, response);
					return null;
				} else {
					Result.ok(null, InfoCode.RESET_ERROR, response);
					return null;
				}
			}
		} catch (Exception e) {
			Result.ok(null, InfoCode.FAILURE, response);
			return null;
		}
		return null;
	}

	/**
	 * @Title: reset @Description: 忘记密码（重置） @date: 2017年1月4日 @author: 星矢 @param
	 *         DriverAccount @param password @param platformId @param
	 *         request @param response @return @throws IOException
	 *         String @throws
	 */
	@RequestMapping(value = "/forget", method = RequestMethod.POST)
	public String reset(@RequestParam String driverAccount, @RequestParam String password, @RequestParam String appId,
			HttpServletRequest request, HttpServletResponse response) throws IOException {
		logger.info("用户---忘记密码重置---driverController/forget");
		request.setCharacterEncoding("UTF-8");
		Driver record = new Driver();
		record.setDriverAccount(driverAccount);
		try {
			List<Driver> selectDriver = driverService.selectDriver(record);
			if (null != selectDriver && selectDriver.size() > 0) {// 登录
				Driver result = selectDriver.get(0);
				result.setUpdateTime(new Date());
				result.setPassword(password);
				if (StringUtils.isNotBlank(appId)) {
					result.setPlatformId(appId);
				}

				int updateDriver = driverService.updateDriver(result);
				if (updateDriver > 0) {
					Result.ok(result, InfoCode.SUCCESS, response);
					return null;
				} else {
					Result.ok(null, InfoCode.FAILURE, response);
					return null;
				}
			} else {
				Result.ok(null, InfoCode.RESET_ERROR, response);
				return null;

			}
		} catch (Exception e) {
			Result.ok(null, InfoCode.FAILURE, response);
			return null;
		}

	}

	/**
	 * @Title: loginout @Description: 退出 @date: 2017年1月4日 @author: 星矢 @param
	 *         DriverAccount @param platformId @param request @param
	 *         response @return @throws IOException String @throws
	 */
	@RequestMapping(value = "/loginout", method = RequestMethod.POST)
	public String loginout(@RequestParam String driverAccount, @RequestParam String appId, HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		logger.info("用户---退出登录---driverController/loginout");
		request.setCharacterEncoding("UTF-8");
		Driver record = new Driver();
		record.setDriverAccount(driverAccount);
		try {
			request.getSession().removeAttribute("LOGIN_DRIVER_ACCOUNT");
			request.getSession(false).removeAttribute("DRIVER_SECURITY_TOKEN");
			Result.ok(null, InfoCode.SUCCESS, response);
			return null;
		} catch (Exception e) {
			Result.ok(null, InfoCode.FAILURE, response);
			return null;
		}
	}

	/**
	 * @Title: updatePass @Description: 修改密码 @date: 2017年1月4日 @author: 星矢 @param
	 *         DriverAccount @param oldPass @param newPass @param
	 *         platformId @param request @param response @return @throws
	 *         IOException String @throws
	 */
	@RequestMapping(value = "/updatePass", method = RequestMethod.POST)
	public String updatePass(@RequestParam String driverAccount, @RequestParam String oldPass,
			@RequestParam String newPass, @RequestParam String appId, HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		logger.info("用户---司机修改登录密码---driverController/updatePass");
		request.setCharacterEncoding("UTF-8");
		Driver record = new Driver();
		record.setDriverAccount(driverAccount);
		record.setPassword(oldPass);

		try {
			List<Driver> selectDriver = driverService.selectDriver(record);
			if (null != selectDriver && selectDriver.size() > 0) {
				Driver result = selectDriver.get(0);
				result.setUpdateTime(new Date());
				result.setPassword(newPass);
				if (StringUtils.isNotBlank(appId)) {
					result.setPlatformId(appId);
				}
				int updateDriver = driverService.updateDriver(result);
				if (updateDriver > 0) {
					Result.ok(result, InfoCode.SUCCESS, response);
					return null;
				} else {
					Result.ok(null, InfoCode.FAILURE, response);
					return null;
				}
			} else {
				Result.ok(null, InfoCode.AUTH_ERROR, response);
				return null;

			}
		} catch (Exception e) {
			Result.ok(null, InfoCode.FAILURE, response);
			return null;
		}

	}
	/**
	 * @Title: regist @Description: 注册 @date: 2017年1月4日 @author: 星矢 @param
	 *         DriverAccount @param verifyCode @param platformId @param
	 *         password @param invitationCode @param request @param
	 *         response @return @throws IOException String @throws
	 */
	@RequestMapping(value = "/regist", method = RequestMethod.POST)
	public String regist(@RequestParam String driverAccount, @RequestParam String verifyCode, String appId,
			@RequestParam String password, String deviceToken, // 推送
			String invitationCode, // 邀请码 预留
			HttpServletRequest request, HttpServletResponse response) throws IOException {
		logger.info("用户---注册---driverController/regist");
		request.setCharacterEncoding("UTF-8");
		if (StringUtils.isNotBlank(invitationCode)) {
			// 预留功能
		}
		// 1 验证码
		// SMSCode sMSCode = new SMSCode();
		// sMSCode.setMobile(driverAccount);
		// sMSCode.setCode(verifyCode);
		try {
			// SMSCode smsCode = sMSCodeIService.findCode(sMSCode);
			// if (smsCode == null) {
			// Result.ok(null, InfoCode.MESSAGE_ERROR, response);
			// return null;
			// }
			// 是否重复注册
			Driver param = new Driver();
			param.setDriverAccount(driverAccount);
			List<Driver> selectDriver = driverService.selectDriver(param);
			if (selectDriver != null && selectDriver.size() > 0) {
				Result.ok(null, InfoCode.REGIST_ERROR, response);
				return null;
			}

			Driver record = new Driver();
			if (StringUtils.isNotBlank(appId)) {
				record.setPlatformId(appId);
			}
			record.setPassword(password);
			record.setDriverPhone(driverAccount);
			record.setDriverAccount(driverAccount);
			record.setOurSecurityToken(TokenProcessor.getInstance().generateToken());
			if (StringUtils.isNoneBlank(deviceToken)) {
				record.setDeviceToken(deviceToken);
			}
			record.setDriverStatus(DriverStatus.WAIT_SUBMIT.getStatus());
			record.setCreateTime(new Date());
			record.setUpdateTime(new Date());

			// 二维码
			String preUrl = ModelConfig.ENV_TEST;
			String rebackUrl = ModelConfig.QR_PIC_DRIVER_LONG_TEST;

			if (ModelConfig.status.equals("1")) {
				preUrl = ModelConfig.ENV_ONLINE;
				rebackUrl = ModelConfig.QR_PIC_DRIVER_LONG_ONLINE;
			}
			String content = preUrl + "driverController/selectInfoByget?driverAccount=" + driverAccount;
			String destPath = ModelConfig.QR_PIC_DRIVER_SHORT;

			String finalPicUrl = QRCodeUtil.encodeDriverOrPay(content, destPath, false);
			StringBuffer sb = new StringBuffer();
			// 回显路径
			String str = sb.append(rebackUrl).append(finalPicUrl).toString();
			// TODO 入库 并返回客户端
			  File file =new File(destPath+finalPicUrl);
              if(file.exists()) {
              	ossutil.putObject("hm/qrInfo/"+finalPicUrl, file);
              // TODO 入库 并返回客户端
              record.setQrInfo("hm/qrInfo/"+finalPicUrl);
              FileUtil.delFile(destPath+finalPicUrl);
              }
			int add = driverService.addDriver(record);
			if (add > 0) {
				// 司机注册活跃统计
				request.getSession().setAttribute("LOGIN_Driver_ACCOUNT", record.getDriverAccount());
				request.getSession(false).setAttribute("Driver_SECURITY_TOKEN", record.getDeviceToken());
				driverService.addHotRecord(record.getId(), "2", "2");
				Result.ok(record, InfoCode.SUCCESS, response);
			} else {
				Result.ok(null, InfoCode.SUCCESS, response);

			}
		} catch (Exception e) {
			e.printStackTrace();
			Result.ok(null, InfoCode.FAILURE, response);
		}
		return null;
	}
	/**
	 * @Title: regist @Description: 注册 @date: 2017年1月4日 @author: 星矢 @param
	 *         DriverAccount @param verifyCode @param platformId @param
	 *         password @param invitationCode @param request @param
	 *         response @return @throws IOException String @throws
	 */
	@RequestMapping(value = "/addDriver", method = RequestMethod.POST)
	public String addDriver(Driver driver, @RequestParam String appId, HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		logger.info("司机管理---添加司机---driverController/addDriver");
		request.setCharacterEncoding("UTF-8");
		try {
			ModelMap modelMap=new ModelMap();
			driverManageLogic.addDriver(driver,appId,modelMap);
			Result.ok(null, (InfoCode)modelMap.get("infoCode"), response);
		} catch (Exception e) {
			e.printStackTrace();
			Result.ok(null, InfoCode.FAILURE, response);
		}
		return null;

//		try {
//			Driver param = new Driver();
//			if (StringUtils.isNotBlank(appId)) {
//				driver.setPlatformId(appId);
//			}
//			// 是否重复注册
//			param.setDriverAccount(driver.getDriverPhone());
//			List<Driver> selectDriver = driverService.selectDriver(param);
//			if (selectDriver != null && selectDriver.size() > 0) {
//				Result.ok(null, InfoCode.REGIST_ERROR, response);
//				return null;
//			}
//			driver = beanPicUtil.cutUrl(driver);
//
//			String pass = NumberUtils.getRandomNumber(6);
//			driver.setDriverAccount(driver.getDriverPhone());
//			driver.setPassword(MD5Util.MD5Encode(MD5Util.MD5Encode(pass, "UTF-8"), "UTF-8"));
//			driver.setOurSecurityToken(TokenProcessor.getInstance().generateToken());
//			driver.setOurSecurityToken(TokenProcessor.getInstance().generateToken());
//			driver.setDriverStatus(DriverStatus.PASS.getStatus());
//			driver.setCreateTime(new Date());
//			driver.setUpdateTime(new Date());
//			driver.setWorkStatus("1");
//
//			// 二维码
//			String preUrl = ModelConfig.ENV_TEST;
//			String rebackUrl = ModelConfig.QR_PIC_DRIVER_LONG_TEST;
//
//			if (ModelConfig.status.equals("1")) {
//				preUrl = ModelConfig.ENV_ONLINE;
//				rebackUrl = ModelConfig.QR_PIC_DRIVER_LONG_ONLINE;
//
//			}
//			String content = preUrl + "driverController/selectInfoByget?driverAccount=" + driver.getDriverAccount();
//			String destPath = ModelConfig.QR_PIC_DRIVER_SHORT;
//
//			String finalPicUrl = QRCodeUtil.encodeDriverOrPay(content, destPath, false);
//			StringBuffer sb = new StringBuffer();
//			// 回显路径
//			String str = sb.append(rebackUrl).append(finalPicUrl).toString();
//			// TODO 入库 并返回客户端
//			driver.setQrInfo(str);
//
//			if (driver.getVehicleTypeId() != null && driver.getVlId() != null) {
//				VtVl vv = new VtVl();
//				vv.setVehicleTypeId(Integer.parseInt(driver.getVehicleTypeId()));
//				vv.setVehicleLengthId(Integer.parseInt(driver.getVlId()));
//				List<VtVl> l = vtVlMapper.selectVtVlList(vv);
//
//				if (l != null && l.size() > 0) {
//					driver.setVtVlId(l.get(0).getId().toString());
//				} else {
//					// 如果不存在，则执行插入，同时向路线-车辆-价格表中新增数据（所有路线均可 包含该车型）
//					VtVl v = new VtVl();
//					if (driver.getVehicleTypeId() != null) {
//						v.setVehicleTypeId(Integer.parseInt(driver.getVehicleTypeId()));
//					}
//					v.setVehicleLengthId(Integer.parseInt(driver.getVlId()));
//					v.setCreateTime(new Date().toLocaleString());
//					int i = vtVlMapper.insertSelective(v);
//					if (i > 0) {
//						driver.setVtVlId(v.getId().toString());
//					}
//					// 获取车型
//					VehicleType vt = new VehicleType();
//					vt.setStatus("0");
//					Route r = new Route();
//					r.setRouteStatus("0");
//					List<Route> route = routeService.selectRoute(null);
//					// 增加一个车型，则所有路线都增加该车型double
//					for (Route route2 : route) {
//						RouteVehiclePrice rvp = new RouteVehiclePrice();
//						rvp.setPrice(new BigDecimal(0));
//						rvp.setRouteId(route2.getId());
//						rvp.setDateTime(new Date().toLocaleString());
//						rvp.setVtVlId(Integer.parseInt(driver.getVtVlId()));
//						rvpService.addRouteVehiclePrice(rvp);
//					}
//
//				}
//			}
//			int add = driverService.addDriver(driver);
//			if (add > 0) {
//				// 发短信
//				// TestSDKClient.testSendSMSE(driver.getDriverAccount(), "【华凌】"
//				// + "恭喜您注册成功 ： 用户名 "+record.getDriverAccount()+" 密码
//				// "+pass+"，请勿向他人泄露。");
//				Result.ok(driver, InfoCode.SUCCESS, response);
//				// Result.ok(record, InfoCode.SUCCESS, response);
//			} else {
//				Result.ok(null, InfoCode.FAILURE, response);
//			}
//		} catch (Exception e) {
//			e.printStackTrace();
//			Result.ok(null, InfoCode.FAILURE, response);
//		}
//		return null;
	}

	/**
	 * 修改司机是否收取配载费
	 * @param driverAccount
	 * @param appId
	 * @param driver
	 * @param type 0：永久收费，1：永久免费，2：免收天数 3：空载免收一次
	 * @param driverStatus
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException
	 */
	@RequestMapping(value = "/updateInfo", method = RequestMethod.POST)
	public String updateInfo(String appId, Driver driver,
							 String type,//0：永久收费，1：永久免费，2：免收天数 3：空载免收一次
			@RequestParam Integer updateBy, HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		logger.info("个人中心/司机管理---更新司机信息/修改司机---driverController/updateInfo");
		request.setCharacterEncoding("UTF-8");
		if (driver == null) {
			Result.ok(null, InfoCode.PARAM_ERROR, response);
			return null; 
		}
		try {
			ModelMap modelMap=new ModelMap();
			if(type!=null&&!type.equals("")) {
				if(type.equals("2")) {
					if(driver.getFreeDay()!=null  && driver.getFreeDay().intValue()!=0 ){
						Calendar freeTime = new GregorianCalendar();
						freeTime.setTime(new Date());
						freeTime.add(Calendar.DAY_OF_MONTH, driver.getFreeDay().intValue()-1);
						freeTime.set(Calendar.HOUR_OF_DAY, 23);
						freeTime.set(Calendar.MINUTE, 59);
						freeTime.set(Calendar.SECOND, 59);
						driver.setFreeTime(freeTime.getTime());
						driver.setIsSecurity("0");
					}
					driver.setNoloadFree(0);
				}else if(type.equals("0")){
					if(driver.getIsSecurity()!=null&&driver.getIsSecurity().equals("0")) {
						if(driver.getFreeDay()==null || driver.getFreeDay().intValue()==0) {
							driver.setFreeTime(null);
							driver.setFreeDayFlag(1);
						}
					}
					driver.setNoloadFree(0);
				}else if(type.equals("3")){
					driver.setNoloadFree(1);
				}else if(type.equals("1")){
					driver.setIsSecurity("1");
				}
			}
			securityFeeTypeHistoryService.save(driver, type, updateBy);
			driverManageLogic.updateDriver(driver,modelMap);
			Result.ok(null, (InfoCode)modelMap.get("infoCode"), response);
		} catch (Exception e) {
			e.printStackTrace();
			Result.ok(null, InfoCode.FAILURE, response);
		}
		return null;
	}

	/**
	 * @Title: updateInfo @Description: 更新司机信息 @date: 2017年1月4日 @author:
	 *         星矢 @param DriverAccount @param platformId @param Driver @param
	 *         request @param response @return @throws IOException
	 *         String @throws
	 */
	@RequestMapping(value = "/auditDriverInfo", method = RequestMethod.POST)
	public String auditDriverInfo(@RequestParam String driverAccount, @RequestParam String appId, Driver driver,
			@RequestParam String driverStatus, HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		request.setCharacterEncoding("UTF-8");
		if (driver == null) {
			Result.ok(null, InfoCode.PARAM_ERROR, response);
			return null;
		}
		if (driverStatus.equals(DriverStatus.FAIL.getStatus()) && StringUtils.isBlank(driver.getDriverUnpassReason())) {
			Result.ok(null, InfoCode.PARAM_ERROR, response);
			return null;
		}
		try {
			Driver param = new Driver();
			param.setDriverAccount(driverAccount);
			driver = beanPicUtil.cutUrl(driver);
			List<Driver> selectDriver = driverService.selectDriver(param);
			if (selectDriver != null && selectDriver.size() > 0) {
				Driver result = selectDriver.get(0);
				driver.setId(result.getId());
				driver.setUpdateTime(new Date());
				// driver.setDriverStatus(DriverStatus.WAIT_AUDIT.getStatus());
				if (StringUtils.isNotBlank(appId)) {
					driver.setPlatformId(appId);
				}

				// 二维码
				String preUrl = ModelConfig.ENV_TEST;
				String rebackUrl = ModelConfig.QR_PIC_DRIVER_LONG_TEST;

				if (ModelConfig.status.equals("1")) {
					preUrl = ModelConfig.ENV_ONLINE;
					rebackUrl = ModelConfig.QR_PIC_DRIVER_LONG_ONLINE;

				}
				String content = preUrl + "driverController/selectInfoByget?driverAccount=" + driverAccount;
				String destPath = ModelConfig.QR_PIC_DRIVER_SHORT;

				String finalPicUrl = QRCodeUtil.encodeDriverOrPay(content, destPath, false);
				StringBuffer sb = new StringBuffer();
				// 回显路径
				String str = sb.append(rebackUrl).append(finalPicUrl).toString();
				// TODO 入库 并返回客户端
				 File file =new File(destPath+finalPicUrl);
	              if(file.exists()) {
	              	ossutil.putObject("hm/qrInfo/"+finalPicUrl, file);
	              // TODO 入库 并返回客户端
	              driver.setQrInfo("hm/qrInfo/"+finalPicUrl);
	              FileUtil.delFile(destPath+finalPicUrl);
	              }
				int update = driverService.updateDriver(driver);
				if (update > 0) {
					if (driverStatus.equals(DriverStatus.PASS.getStatus())) {
						Driver userParam3 = new Driver();
						userParam3.setDriverAccount(driverAccount);
						List<Driver> selectdriver2 = driverService.selectDriver(userParam3);
						if (selectdriver2 != null && selectdriver2.size() > 0) {
							Driver driver2 = selectdriver2.get(0);

							if (StringUtils.isNotBlank(driver2.getDeviceToken())) {
								Push push = new Push();
								push.setPtype(3);
								push.setPushoid("");
								push.setContext("恭喜您，资料已审核成功，马上开始接单吧");// 要发送的内容
								push.setDisplayType("notification");// message:
																	// 消息，通知：notification
								push.setOperationType(1);// 用户类型：1司机，2发货端
								push.setPushClient("driverPushClient");// 使用的推送Client
								push.setPushType("listcast");// unicast：单播 //
																// listcast：列表
								push.setTitle("资料审核通过"); // 发送的标题
								push.setTokenStr(new String[] { driver2.getDeviceToken() }); // 要发送手机的token
								// ios & android推送公共调用方法
								pushToAppIService.pushCommon(push);
							}
						}
					}
				}
				Result.ok(null, InfoCode.SUCCESS, response);

				return null;
			} else {
				Result.ok(null, InfoCode.PARAM_ERROR, response);
				return null;
			}

		} catch (Exception e) {
			e.printStackTrace();
			Result.ok(null, InfoCode.FAILURE, response);
		}
		return null;
	}

	@RequestMapping(value = "/selectInfo", method = RequestMethod.POST)
	public String selectInfo(@RequestParam String driverAccount, HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		logger.info("个人中心/司机管理---司机详情/司机详情---driverController/selectInfo");
		request.setCharacterEncoding("UTF-8");
		try {
			Driver param = new Driver();
			param.setDriverAccount(driverAccount);
			List<Driver> selectDrivercheck = driverService.selectDriver(param);
			if (selectDrivercheck != null && selectDrivercheck.size() > 0) {
				Driver d = selectDrivercheck.get(0);
				d.setPassword(null);
				//TODO 有疑惑
				if (d.getVehicleTypeId() != null) {
					param.setDriverStatus(d.getDriverStatus());
				}
			} else {
				Result.ok(null, InfoCode.SUCCESS, response);
			}
			List<Driver> selectDriver = driverService.selectDriverInfo(param);
			if (selectDriver != null && selectDriver.size() > 0) {
				//可用余额
				BigDecimal remainCash = selectDriver.get(0).getRemainCash();
				if(remainCash==null) {
					 selectDriver.get(0).setRemainCash(new BigDecimal(0));
				}
				selectDriver.get(0).setUsableCash(remainCash.subtract(selectDriver.get(0).getWithdrawCash()));
				Driver modifyUrl =selectDriver.get(0);

				DriverAmountInfo selectDriverHistory = driverService.selectDriverHistory(modifyUrl.getId());
				if(modifyUrl.getWithdrawCash()!=null&&modifyUrl.getWithdrawCash().compareTo(new BigDecimal(0))>0) {
					BigDecimal remainCash1 = modifyUrl.getRemainCash();
					if(remainCash1==null) {
						modifyUrl.setRemainCash(new BigDecimal(0));
					}
					BigDecimal giveCash = selectDriverHistory.getGiveCash();
					BigDecimal subedRewardCash = selectDriverHistory.getSubedRewardCash();
					BigDecimal subtract = giveCash.subtract(subedRewardCash);
					BigDecimal remainCashReal2 = modifyUrl.getRemainCash().subtract(modifyUrl.getWithdrawCash()).subtract(subtract);
					modifyUrl.setRemainCash(remainCashReal2);
					logger.info("当前提现金额"+modifyUrl.getWithdrawCash()+"总奖励金额"+giveCash+"已扣减奖励金额"+subedRewardCash+"应扣减奖励金额"+subtract);
				}
				//TODO 需要查看是否需要此逻辑
				if (modifyUrl.getNoloadFree().equals(1)) {
					modifyUrl.setIsSecurity("1");
				}else{
					if(modifyUrl.getIsSecurity().equals("0")) {
						Date freeTime = modifyUrl.getFreeTime();
						Date current = new Date();
						if(freeTime!=null) {
							if(freeTime.getTime()>current.getTime()) {
								modifyUrl.setIsSecurity("1");
							}
						}
					}
				}
				List<DriverVehicle> driverVehicles = driverVehicleService.selectByIdAndNumberAndState(modifyUrl.getId(),null,
						DriverVehicleStatus.PASS.getStatus().toString());
			    if(driverVehicles!=null && driverVehicles.size()>0){
					DriverVehicle driverVehicle=driverVehicles.get(0);
					modifyUrl.setVtVlId(driverVehicle.getId().toString());
					modifyUrl.setDrivingLicense(driverVehicle.getDrivingLicense());
					modifyUrl.setDrivingLicensePic(driverVehicle.getDrivingLicensePic());
					modifyUrl.setDrivingGuaPic(driverVehicle.getDrivingGuaPic());
					if(driverVehicle.getVehicleLengthId()!=null){
						modifyUrl.setVlId(driverVehicle.getVehicleLengthId().toString());
						VehicleLength vehicleLength=vehicleLengthService.selectByPrimaryKey(driverVehicle.getVehicleLengthId());
						if (vehicleLength!=null) {
							modifyUrl.setVehicleLength(vehicleLength.getVehicleLength()==null?"":vehicleLength.getVehicleLength().toString());
						}
					}
					if(driverVehicle.getVehicleTypeId()!=null){
						modifyUrl.setVehicleTypeId(driverVehicle.getVehicleTypeId().toString());
						VehicleType vehicleType = vehicleTypeService.selectByPrimaryKey(driverVehicle
								.getVehicleTypeId());
						if (vehicleType!=null) {
							modifyUrl.setVehicleLoad(vehicleType.getVehicleLoad()==null?"":vehicleType.getVehicleLoad().toString());
							modifyUrl.setVehicleWidth(vehicleType.getVehicleWidth()==null?"":vehicleType.getVehicleWidth().toString());
						}
					}
					modifyUrl.setRoadTransportCertificateNumber(driverVehicle.getTransportLicense());
					modifyUrl.setPlateNumber(driverVehicle.getPlateNumber());
					modifyUrl.setPlateNumberPic(driverVehicle.getPlateNumberPic());
				}
				beanPicUtil.modifyUrl(modifyUrl);
				Result.ok(modifyUrl, InfoCode.SUCCESS, response);
			} else {
				Result.ok(null, InfoCode.SUCCESS, response);
			}

		} catch (Exception e) {
			e.printStackTrace();
			Result.ok(null, InfoCode.SUCCESS, response);
		}
		return null;
	}

	@RequestMapping(value = "/selectInfoByget", method = RequestMethod.GET)
	public String selectInfoByget(@RequestParam String driverAccount, String qrFlag, Integer channel, // 渠道，默认干线渠道为1
																										// 线下为2
																										// ，不传为1
			HttpServletRequest request, HttpServletResponse response) throws IOException {
		logger.info("订单---获取通行证信息---driverController/selectInfoByget");
		request.setCharacterEncoding("UTF-8");
		try {
			Driver param = new Driver();
			param.setDriverAccount(driverAccount);
			List<Driver> selectDrivercheck = driverService.selectDriver(param);
			
			
			
			if (selectDrivercheck != null && selectDrivercheck.size() > 0) {
				Driver d = selectDrivercheck.get(0);
				//TODO 有疑惑
				if (d.getVehicleTypeId() != null) {
					param.setDriverStatus(d.getDriverStatus());
				}
			} else {
				Result.ok(null, InfoCode.SUCCESS, response);
			}
			List<Driver> selectDriver = driverService.selectDriverInfo(param);
			// TODO
			if (channel == null) {
				channel = 1;
			}
			ChannelDiscount selectByPrimaryKey = channelDiscountMapper.selectByPrimaryKey(channel);
			if (selectDriver != null && selectDriver.size() > 0) {
				Driver t = selectDriver.get(0);
				
				
				
				
				t.setPassword(null);
				if (t.getQrFlag() == null && qrFlag == null) {

				} else if (t.getQrFlag() != null && qrFlag == null) {
					Result.ok(null, InfoCode.SUCCESS, response);
					return null;
				} 
				else if (t.getQrFlag() != null && "".equals(qrFlag)) {
					Result.ok(null, InfoCode.SUCCESS, response);
					return null;
				} else if (t.getQrFlag() == null && "".equals(qrFlag)) {
				} else {
					if (qrFlag != null && !qrFlag.equals("")) {
						if (!qrFlag.equals(t.getQrFlag())) {
							Result.ok(null, InfoCode.SUCCESS, response);
							return null;
						}
					}
					
				}
				
				Driver modifyUrl = beanPicUtil.modifyUrl(t);
				BigDecimal remainCash = modifyUrl.getRemainCash();
				if(remainCash==null) {
					modifyUrl.setRemainCash(new BigDecimal(0));
				}

				modifyUrl.setChannelDiscount(selectByPrimaryKey);
				
				DriverAmountInfo selectDriverHistory = driverService.selectDriverHistory(modifyUrl.getId());
				if(modifyUrl.getWithdrawCash()!=null&&modifyUrl.getWithdrawCash().compareTo(new BigDecimal(0))>0) {
					BigDecimal giveCash = selectDriverHistory.getGiveCash();
					BigDecimal subedRewardCash = selectDriverHistory.getSubedRewardCash();
					BigDecimal subtract = giveCash.subtract(subedRewardCash);
					BigDecimal remainCashReal2 = modifyUrl.getRemainCash().subtract(modifyUrl.getWithdrawCash()).subtract(subtract);
					modifyUrl.setRemainCash(remainCashReal2);
					logger.info("当前提现金额"+modifyUrl.getWithdrawCash()+"总奖励金额"+giveCash+"已扣减奖励金额"+subedRewardCash+"应扣减奖励金额"+subtract);
				}
				modifyUrl.setUsableCash(modifyUrl.getRemainCash());
				if (modifyUrl.getNoloadFree().equals(1)) {
					modifyUrl.setIsSecurity("1");
				}else{
					if(modifyUrl.getIsSecurity().equals("0")) {
						Date freeTime = modifyUrl.getFreeTime();
						Date current = new Date();
						if(freeTime!=null) {
							if(freeTime.getTime()>current.getTime()) {
								modifyUrl.setIsSecurity("1");
							}
						}
					}
				}

			    STSPrice sts=new STSPrice();
			    sts.setStsStatus(0);
			    sts.setIsFullLoad(0);
				List<STSPrice> stsPriceList=stsPriceService.selectListBySelective(sts);
				List<DriverVehicle> driverVehicles = driverVehicleService.selectByDIVI(modifyUrl.getId(),
						null);
				if (driverVehicles!=null) {
					if(stsPriceList!=null){
						Iterator<DriverVehicle> iterator = driverVehicles.iterator();
						DriverVehicle dv=null;
						while (iterator.hasNext()){
							dv=iterator.next();
							if(dv.getStatus()==0 || dv.getStatus()==1){
								for (STSPrice stsPrice : stsPriceList) {
									if(dv.getVehicleTypeId().equals(stsPrice.getVehicleTypeId())){
										dv.setStsPrice(stsPrice.getStsPrice());
										dv.setStsVehicleType(stsPrice.getStsVehicleType());
										dv.setVehicleTypeName(stsPrice.getVehicleTypeName());
										break;
									}
								}
							}else{
								iterator.remove();
							}
						}
					}
				}
				modifyUrl.setVehicleList(driverVehicles);
				Result.ok(modifyUrl, InfoCode.SUCCESS, response);
			} else {
				Result.ok(null, InfoCode.SUCCESS, response);
			}

		} catch (Exception e) {
			e.printStackTrace();
			Result.ok(null, InfoCode.SUCCESS, response);
		}
		return null;
	}

	@RequestMapping(value = "/updateDeviceToken", method = RequestMethod.POST)
	public String updateDeviceToken(@RequestParam String driverAccount, @RequestParam String deviceToken, // 推送
			String appId, HttpServletRequest request, HttpServletResponse response) throws IOException {
		try {
			request.setCharacterEncoding("UTF-8");
			Driver param = new Driver();
			param.setDriverAccount(driverAccount);
			List<Driver> selectUser = driverService.selectDriver(param);
			if (selectUser == null) {
				Result.ok(null, InfoCode.PARAM_ERROR, response);
				return null;
			}

			Driver record = new Driver();
			if (StringUtils.isNotBlank(appId)) {
				record.setPlatformId(appId);
			}
			record.setDriverAccount(driverAccount);
			if (StringUtils.isNoneBlank(deviceToken)) {
				record.setDeviceToken(deviceToken);
			}
			record.setId(selectUser.get(0).getId());
			record.setUpdateTime(new Date());
			int add = driverService.updateDriver(record);
			if (add > 0) {
				Result.ok(null, InfoCode.SUCCESS, response);
			} else {
				Result.ok(null, InfoCode.FAILURE, response);

			}
		} catch (Exception e) {
			Result.ok(null, InfoCode.FAILURE, response);
		}
		return null;
	}

	/**
	 * 当前进行中的订单 1：当前订单列表 2：订单收入列表，3历史订单列表 4 所有订单列表
	 * 
	 * @param driverId
	 * @param pageId
	 * @param pageCount
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException
	 */
	@RequestMapping(value = "/selectOrderList", method = RequestMethod.POST)
	public String selectOrderList(@RequestParam Integer type, @RequestParam Integer driverId,
			@RequestParam Integer pageId, @RequestParam Integer pageCount, HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		logger.info("订单业务---获取当前订单列表/订单收入列表---driverController/selectOrderList");
		request.setCharacterEncoding("UTF-8");
		try {
			AppPager handle = AppPager.handle(pageId, pageCount);
			Order param = new Order();
			param.setPageId(handle.getPageId());
			param.setPageCount(handle.getPageCount());

			/*
			 * orderstatus1：待接单 2：待付款（已接单） 3：待送达（已付款） 4：待点评 5：待打款（线下给司机打款）
			 * 6：已完成（已打款） 20：关闭（取消/关闭）
			 */
			Map map = new HashMap<>();
			OrderVO o = driverService.selectOrderOtherInfo(driverId);
			if (type == 1) {
				param.setDriverId(driverId);
				param.setOrderStatus("13"); // orderStatus 2.3.4
			} else if (type == 2) {
				param.setDriverId(driverId);
				param.setOrderStatus("14"); // orderStatus 5,6
			} else if (type == 3) {
				param.setDriverId(driverId);
			} else if (type == 4) {
				param.setDriverId(driverId);
			} else {
				param.setDriverId(driverId);
				param.setOrderStatus("6"); // 已打款订单
			}
			map.put("totalIncome", o.getTotalIncome());
			map.put("totalOrderCount", o.getTotalOrderCount());
			map.put("successOrderCount", o.getSuccessOrderCount());
			map.put("favourableCommentPercent", o.getFavourableCommentPercent());
			List<Order> orderList = orderService.selectOrder(param);
			map.put("orderList", orderList);
			Result.ok(map, InfoCode.SUCCESS, response);
		} catch (Exception e) {
			e.printStackTrace();
			Result.ok(null, InfoCode.FAILURE, response);
		}
		return null;
	}

	/**
	 * 司机点击确认送达
	 * 
	 * @param orderCode
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException
	 */
	@RequestMapping(value = "/driverConfirmOrder", method = RequestMethod.POST)
	public String driverConfirmOrder(@RequestParam String orderCode, HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		logger.info("订单业务---司机确认送达---driverController/driverConfirmOrder");
		request.setCharacterEncoding("UTF-8");
		try {
			Order orderParam = new Order();
			orderParam.setOrderCode(orderCode);
			List<Order> selectOrder = orderService.selectOrder(orderParam);
			if (selectOrder != null && selectOrder.size() > 0) {
				Order order = selectOrder.get(0);
				String orderStatus = order.getOrderStatus();
				if (orderStatus.equals(OrderStatus.TO_ARRIVE.getStatus())
						|| orderStatus.equals(OrderStatus.TO_COMMENT.getStatus())) {
					order.setDriverEnsureStatus("2");
					order.setDriverEnsureTime(new Date());
					int updateOrderById = orderService.updateOrderById(order);
					if (updateOrderById > 0) {

						User user = new User();
						user.setUserAccount(order.getUserAccount());
						List<User> selectUser = userService.selectUser(user);

						if (selectUser != null && selectUser.size() > 0) {
							User user2 = selectUser.get(0);
							// push
							if (StringUtils.isNotBlank(user2.getUserAccount())
									&& StringUtils.isNotBlank(user2.getDeviceToken())) {
								Push push = new Push();
								push.setPtype(1);
								push.setPushoid(order.getOrderCode());
								push.setContext("您的货物已妥善送达，请尽快确认收货。");// 要发送的内容
								push.setDisplayType("notification");// message:
																	// 消息，通知：notification
								push.setOperationType(2);// 用户类型：1司机，2发货端
								push.setPushClient("consignerPushClient");// 使用的推送Client
																			// 是往发货端：consignerPushClient
																			// 或
																			// 司机端发送：driverPushClient。
								push.setPushType("listcast");// unicast：单播
																// //
																// listcast：列表
								push.setTitle("货物送达"); // 发送的标题
								push.setTokenStr(new String[] { user2.getDeviceToken() }); // 要发送手机的token
								// ios & android推送公共调用方法
								pushToAppIService.pushCommon(push);
							}
						}
					} else {
						Result.ok(null, InfoCode.FAILURE, response);
						return null;
					}
					Result.ok(null, InfoCode.SUCCESS, response);
					return null;
				}
			}
		} catch (Exception e) {
			Result.ok(null, InfoCode.FAILURE, response);
		}
		Result.ok(null, InfoCode.SUCCESS, response);
		return null;
	}

	// 上报司机坐标
	@RequestMapping(value = "/uploadLocation", method = RequestMethod.POST)
	public String uploadLocation(@RequestParam Double lat, @RequestParam Double lng,
			@RequestParam(value = "driverId", required = false) Integer driverId, HttpServletRequest request,
			HttpServletResponse response) {
		logger.info("司机经纬度---上传司机经纬度---driverController/uploadLocation");
		if (null == lat || null == lng || "null".equals(lat) || "null".equals(lng)) {
			Result.ok(null, InfoCode.FAILURE, response);
			return null;
		}
		int i = 0;
		DriverLatitudeLongitude dll = new DriverLatitudeLongitude();
		dll.setLat(lat);
		dll.setLng(lng);

		if (driverId != null && !("null".equals(driverId))) {
			dll.setDriverId(driverId);
			;
		}
		i = dllService.operDriverLatitudeLongitude(dll);
		if (i > 0) {
			Result.ok(null, InfoCode.SUCCESS, response);
			return null;
		} else {
			Result.ok(null, InfoCode.FAILURE, response);
		}
		return null;
	}

	// 上报司机坐标
	@RequestMapping(value = "/getDriverLocation", method = RequestMethod.POST)
	public String getDriverLocation(@RequestParam(value = "driverId", required = true) Integer driverId,
			HttpServletRequest request, HttpServletResponse response) {
		logger.info("司机经纬度---获取司机经纬度---driverController/getDriverLocation");
		if (null == driverId || "null".equals(driverId)) {
			Result.ok(null, InfoCode.FAILURE, response);
			return null;
		}
		int i = 0;
		DriverLatitudeLongitude dll = new DriverLatitudeLongitude();
		dll.setDriverId(driverId);
		;
		List<DriverLatitudeLongitude> ddlList = dllService.selectDriverLatitudeLongitude(dll);
		if (ddlList != null && ddlList.size() > 0) {
			Result.ok(ddlList.get(0), InfoCode.SUCCESS, response);
			return null;
		} else {
			Result.ok(null, InfoCode.SUCCESS, response);
		}
		return null;
	}

	// 获取司机经纬度信息
	@RequestMapping(value = "/getAllDriverLocation", method = RequestMethod.POST)
	public String getAllDriverLocation(@RequestParam(value = "driverId", required = false) Integer driverId,
			HttpServletRequest request, HttpServletResponse response) {
		logger.info("司机经纬度---所有司机经纬度信息---driverController/getAllDriverLocation");
		// if(null == driverId || "null".equals(driverId)){
		// Result.ok(null, InfoCode.FAILURE, response);
		// return null;
		// }
		int i = 0;
		// DriverLatitudeLongitude dll = new DriverLatitudeLongitude();
		// dll.setDriverId(driverId);;
		List<DriverLatitudeLongitude> ddlList = dllService.selectDriverLatitudeLongitude(null);
		DriverLatitudeLongitudeVO lVo = new DriverLatitudeLongitudeVO();
		if (ddlList != null && ddlList.size() > 0) {
			List driverList = driverService.selectDriver(null); // 司机总数量==车辆总数量
			Order order = new Order();
			order.setOrderStatus("13"); // 进行中
			List orderList = new ArrayList<>();
			orderList = orderService.selectOrder(order);
			if (driverList != null && driverList.size() > 0) {
				lVo.setBusyCount(orderList.size());
				lVo.setFreeCount(driverList.size() - orderList.size());
			}
			lVo.setLlList(ddlList);
			Result.ok(lVo, InfoCode.SUCCESS, response);
			return null;
		} else {
			Result.ok(null, InfoCode.SUCCESS, response);
		}
		return null;
	}

	/********************************************************
	 * ******** ******** 后台功能 ******** ******** ******** ********
	 ******************************************************/
	/*
	 * 1. 待提交 2. 待审核 3. 已通过 4. 未通过 5. 无效
	 */
	@RequestMapping(value = "/backSelectDriverList", method = RequestMethod.POST)
	public String backSelectDriverList(Driver driver,
									   @RequestParam Integer pageId, @RequestParam Integer pageCount,
			HttpServletRequest request, HttpServletResponse response) {
		logger.info("司机管理---司机列表---driverController/backSelectDriverList");
		try {
			AppPager handle = AppPager.handle(pageId, pageCount);
			
			driver.setPageId(handle.getPageId());
			driver.setPageCount(handle.getPageCount());
			
			List<Driver> ddlList = driverService.selectDriverInfo(driver);
			driverService.fillChargeSetting(ddlList);
			driver.setPageCount(null);
			driver.setPageId(null);
//			List<Driver> list = driverService.selectDriverInfo(driver);
//			driver.setPageCount(null);
//			driver.setPageId(null);
//			int selectDriverCount = driverMapper.selectDriverCount(driver);
			
			Map<String, Object> pageInfo = AppPager.getPageInfo(ddlList, pageCount, ddlList.size(), pageId);
			
			Result.ok(pageInfo, InfoCode.SUCCESS, response);
			return null;
		} catch (Exception e) {
			e.printStackTrace();
			Result.ok(null, InfoCode.FAILURE, response);
			return null;
		}
	}

	@RequestMapping(value = "/addRemainCashDesc", method = RequestMethod.POST)
	public String backSelectDriverList(RemainCashDesc r, HttpServletRequest request, HttpServletResponse response) {
		logger.info("余额说明管理---添加---driverController/addRemainCashDesc");
		try {
			List<RemainCashDesc> ddlList = rdm.selectRemainCashDesc(null);

			if (ddlList != null && ddlList.size() > 0) {
				RemainCashDesc rd = ddlList.get(0);
				r.setId(rd.getId());
				rdm.updateByPrimaryKey(r);
				Result.ok(ddlList, InfoCode.SUCCESS, response);
				return null;
			} else {
				rdm.insertSelective(r);
				Result.ok(null, InfoCode.SUCCESS, response);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;

	}

	@RequestMapping(value = "/selectRemainCashDesc", method = RequestMethod.POST)
	public String selectRemainCashDesc(RemainCashDesc r, HttpServletRequest request, HttpServletResponse response) {
		logger.info("余额说明管理---查询---driverController/selectRemainCashDesc");
		try {
			List<RemainCashDesc> ddlList = rdm.selectRemainCashDesc(null);
			if (ddlList != null && ddlList.size() > 0) {
				Result.ok(ddlList.get(0), InfoCode.SUCCESS, response);
				return null;
			} else {
				Result.ok(null, InfoCode.SUCCESS, response);
				return null;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;

	}
	@Autowired
	VehicleMapper vehicleMapper;
	@RequestMapping(value = "/sendLoginkByOrderCode", method = RequestMethod.POST)
	public String loginkTest(String orderCode, HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		Order o = new Order();
		o.setOrderCode(orderCode);
		List<Order> ol = orderService.selectByPrimaryKeySelective(o);
		if (ol != null && ol.size() > 0) {
			Order order = ol.get(0);
			if (order.getLoginkStatus() == 0) {
				Driver d = new Driver();
				if (order.getDriverPhone() != null) {
					d.setDriverAccount(ol.get(0).getDriverPhone());
					// 此处验证车牌号
					if(order.getPlateNumber()!=null){
						String plateNumber=order.getPlateNumber(); // 从order中获取车牌号
						Vehicle  v = vehicleMapper.selectByPlateNumber(plateNumber);
						if(v!=null && v.getPeriodTime()!=null && v.getPeriodTime().after(new Date())  && v.getRwStatus()==0){ // 车牌号验证通过
							List<Driver> dl = driverService.selectDriverInfo(d);
							if (dl != null && dl.size() > 0) {
								dl.get(0).setPlateNumber(plateNumber);
								if(v.getRoadTransportCertificateNumber()!=null) {
									dl.get(0).setRoadTransportCertificateNumber(v.getRoadTransportCertificateNumber());
								}
								if(order.getPayPrice()!= null && order.getPayPrice().compareTo(new BigDecimal(1000000))==-1) {
									int result = loginkUtil.sendXml(order, dl.get(0), Integer.parseInt(ModelConfig.status));
									if (result == 1) { // update order getLoginkStatus is 1
										Order oo = new Order();
										oo.setId(order.getId());
										oo.setLoginkStatus(1);
										oo.setLoginkTime(new Date());
										orderService.updateOrderById(oo);
									}
								}else {
									logger.info("金额超出限制");
								}
							}else{
								logger.info("司机信息未查询到");
							}
						}else {
							logger.info("车辆未入网或道路许可证过期");
						}
					}
				}else{
					logger.info("订单表中司机手机号码为空");
				}
			}
		}else{
			logger.info("订单未查询到");
		}
		return null;
	}

	@RequestMapping(value = "/sendLoginkByOrderCodeList", method = RequestMethod.POST)
	public String sendLoginkByOrderCodeList(HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		Order o = new Order();
		o.setOrderStatus("15");
		o.setLoginkStatus(0);
		List<Order> ol = orderMapper.selectOrderForLogink(o);
		if (ol != null && ol.size() > 0) {
			int j = 0;
			for (Order order : ol) {
				if (order.getLoginkStatus() == 0) {
					Driver d = new Driver();
					if (order.getDriverPhone() != null) {
						d.setDriverAccount(order.getDriverPhone());
						List<Driver> dl = driverService.selectDriverInfo(d);
						if (dl != null && dl.size() > 0) {
							Driver driver = dl.get(0);
							if (driver.getRoadTransportCertificateNumber() != null
									&& driver.getRoadTransportCertificateNumber() != ""
									&& !"123456789".equals(driver.getRoadTransportCertificateNumber())) {
								int result = loginkUtil.sendXml(order, driver, Integer.parseInt(ModelConfig.status));
								if (result == 1) { // update order
													// getLoginkStatus with 1
									Order oo = new Order();
									oo.setId(order.getId());
									oo.setLoginkStatus(1);
									orderService.updateOrderById(oo);
									System.out.println("LOG-send success:" + j++);
								}
							}
						}else{
							logger.info("司机信息未查询到");
						}
					}else{
						logger.info("订单表中司机手机号码为空");
					}
				}
			}

		}
		return null;
	}
	public static void main(String[] args) {
	
		Calendar freeTime = Calendar.getInstance();
		freeTime.setTime(new Date());
		freeTime.add(Calendar.DAY_OF_MONTH, 0);
		freeTime.set(Calendar.HOUR_OF_DAY, 23);
		freeTime.set(Calendar.MINUTE, 59);
		freeTime.set(Calendar.SECOND, 59);
		System.out.println(new Date());
		System.out.println(freeTime.getTime());
	}
}
